# -*- coding:utf-8 -*-

import os
import sys
import getopt
import datetime
import shutil
import subprocess
import plistlib
import platform
import subprocess
import unity_realtime_log

#检查相关环境变量
def checkEnvironVariate(export):
    variate = os.environ.get(export)
    #if variate == None:
       # print '未定义的环境变量:=> ',export
        #sys.exit(0)
        #pass
    osName = platform.system()
    if osName == "Windows":
        return variate
    return "/Applications/Unity/Unity.app/Contents/MacOS/Unity"

SVN_UPDATE_CMD = 'svn update'
SVN_CHECKOUT_CMD = 'svn checkout http://172.16.1.57/svn/op_new/trunk/client'
SVN_REVERT_CMD = 'svn revert -R 100' # 回退整个文件夹至服务器最新版本
SVN_COMMIT_CMD = 'svn commit -m "jenkines auto commit" '
SVN_ADD_CMD = 'svn add '
SVN_GET_VERSION_NUM = 'svn --username "tanzhu" --password "tanzhu" info '
SVN_VERSION_INFO ='svn info http://172.16.1.57/svn/op_new/trunk/client'

UNITY_PATH = checkEnvironVariate('UNITY_PATH')  # unity.exe 目录
SVN_VERSION = 'null'                            # svn 当前提交版本号
VERSION_VALUE = '1.0.0'                         #xcode 的version_value
CODE_VALUE = '0'                                #xcode 的build 版本号
ProjectInfoListPath = 'client/ProjectAll/Assets/Editor/IOSPorter/ChannelConfig/opensdk_ali'
BUILDINFO_PATH = os.getcwd() + '/%s/Info.plist' %(ProjectInfoListPath) #info.plit路径  os.getcwd 运行脚本的目录
IPA_PATH = os.getcwd() + '/ipa'                 # ipa 路径
BUILD_MODE = ["dev","dist"]
BUILD_STATUS = 'Release'
TARGET_NAME = 'Unity-iPhone'
PRODUCE_NAME = 'endlessrunnerbase'              #

#获取SVN 的哈希code
def getSvnVersionHashCode():
    info = os.popen(SVN_VERSION_INFO).readlines()
    for line in info:
        if(line.startswith("Revision: ")):
            SVN_VERSION = line.replace("Revision: ",'').strip('\r\n')
            #break

    VERSION_VALUE = "1.1."+SVN_VERSION
    CODE_VALUE ="1.2."+SVN_VERSION


#获取当前版本号 和 code 值 ,  两个版本号最好也自动获取
def getBundleVersion():
    if(os.path.exists(BUILDINFO_PATH)):
        try:
            plist = plistlib.readPlist(BUILDINFO_PATH)
            VERSION_VALUE = plist["CFBundleShortVersionString"]
            CODE_VALUE = plist["CFBundleVersion"]
        except Exception as e :
            print "info.plist 解析失败 ：" + BUILDINFO_PATH ,e
        return
    else:
        print  "没有找到Info.Plist文件："+ BUILDINFO_PATH


#修改当前版本号和CODE值
def modifyBundleVersion():
    if(os.path.exists(BUILDINFO_PATH)):
        #用plistlib.writePlist方法必须要重新覆盖整个info.plist , /
        #  这边用系统的PlistBuddy方法修改
        osName = platform.system()
        if osName == 'Darwin':
            os.system('/usr/libexec/PlistBuddy -c '
                  ' "Set:CFBundleShortVersionString %s" %s' % (VERSION_VALUE,BUILDINFO_PATH))
            os.system('/usr/libexec/PlistBuddy -c '
                  ' "Set:CFBundleVersion %s" %s' % (CODE_VALUE,BUILDINFO_PATH))
            print "修改mac 上Version"


#对工程下载更新
def downLoadUnityProject():
    cwd = os.getcwd()
    #判断库工程是否存在 , 如果存在执行svn pull , 否则执行 svn clone
    if (os.path.exists('client')):
        os.chdir('client') #变更当前工作目录
        os.system(SVN_UPDATE_CMD)
        print os.getcwd()
        pass
    else:
        #下载库工程
        os.system(SVN_CHECKOUT_CMD)
    pass
    os.chdir(cwd)
    return


#从Unity导出xcode工程
def exportXcodeProj(projectPath):
    #cmd =UNITY_PATH+"\Unity.exe -projectPath "+os.getcwd()+'\client\ProjectAll' + " -executeMethod ProjectBuild.BuildForIPhone "+VERSION_VALUE +" "+CODE_VALUE+" -quit"

   # testProjPath = os.getcwd() + '\IOSBuild' #项目工程目录
    methodArgs ="JenkinsArgs;opensdk_ali;"+os.path. os.getcwd()+"\XCodeProj";  #xcode输出目录
    logFilePath = os.getcwd() + "\_kellylog.txt" # 日志文件路径
    osName = platform.system()
    print osName
    if osName == 'Windows':
        #cmd = "Unity -projectPath "+ testProjPath +" -quit -batchmode -executeMethod " + " XCodeProjectBuilder.CommandLineArgsRun "+  methodArgs + " -logFile "+logFilePath
        unity_realtime_log.build("XCodeProjectBuilder.CommandLineArgsRun", UNITY_PATH, projectPath, methodArgs,
                                 logFilePath)
    elif osName == 'Darwin': # Mac
        #cmd = UNITY_PATH+" -projectPath "+ testProjPath +" -quit -batchmode -executeMethod " + " XCodeProjectBuilder.CommandLineArgsRun "+  methodArgs + " -logFile "+logFilePath
        unity_realtime_log.build("XCodeProjectBuilder.CommandLineArgsRun", UNITY_PATH, projectPath, methodArgs,
                                 logFilePath)

    print "OK!,导出Xcode 工程完成"


#创建ipa文件夹
def makeIpaFile():
    if(os.path.exists(IPA_PATH)):
        cmd = "find ./ipa -type f -name \"*.ipa\" | xargs rm -rf"
        os.system(cmd)
    else:
        #创建新文件夹
        os.system("mkdir "+IPA_PATH)


#git 下载相关工程设置
def updatePodFileAndInstall():
    tmp = os.getcwd();
    podPath = os.getcwd()+'/XCodeProj';
    if(os.path.exists(podPath)):
        os.chdir(podPath)
        cmd = 'pod install'
        os.system(cmd)
    else:
        print 'Pod 更新目录不存在！！！ => ' + 'podPath'
    #变更回原目录
    os.chdir(tmp)


#编译库工程
def buildLibSg():
    tmp = os.getcwd();
    libPath = './lib_sg_projects/lib_common_ios/'
    if (os.path.exists(libPath)):
        os.chdir(libPath)
        cmd = "xcodebuild -target SG_project_ios -configuration "+ BUILD_STATUS + " -sdk iphoneos build"
        os.system(cmd)
    else:
        print "库工程不存在，请确认是否从git中获取成功: "+libPath
        os.system.exit(0)
    #变更回原来工作目录
    os.chdir(tmp)


#编译主工程
def buildTarget():
    tmp = os.getcwd()
    os.chdir('./XcodeProj')
    cmd = 'xcodebuild -target %s -configuration %s -sdk iphoneos build  ' %\
    (TARGET_NAME, BUILD_STATUS)
    #cmd = 'xcodebuild -target %s -sdk %s -configuration %s GCC_PREPROCESSOR_DEFINITIONS="%s" build'
    #%(project,,SDK,configuration,definitions)
    os.system(cmd)
    #回到原目录
    os.chdir(tmp)


#sign and package 签名和打包
def packageIpa():
    ORIIPA_PATH = os.getcwd()+'/XcodeProj/build' +BUILD_STATUS+"-iphoneos/"+PRODUCE_NAME+".app"
    cmd = 'xcrun -sdk iphoneos PackageApplication -v %s -o %s/UnclearRun_%s.ipa' \
    %(ORIIPA_PATH,IPA_PATH,BUILD_STATUS)
    os.system(cmd)

#根据打包模式打包
def execute_makeipa(buildmode):
    global BUILD_STATUS
    CODE_SIGN_IDENTITY = ""
    PROVISONNIING_PROFILE =""

    print buildmode

    if 'dev' == buildmode:
        BUILD_STATUS = 'Debug'
        #cmd = "find "+os.getcwd()+"/mobileProvision/dev -type f -name \"*.mobileprovision\""
        #PROVISONNIING_PROFILE = os.popen(cmd).read()
        #CODE_SIGN_IDENTITY = "iPhone Developer: xxxxxxx"
    else:
        BUILD_STATUS = 'Release'
        #cmd = "find "+os.getcwd()+"/mobileProvision/dist -type f -name \"*.mobileprovision\""
        #PROVISONNING_PROFILE = os.popen(cmd).read()
        #CODE_SIGN_IDENTITY = "iPhone Distribution: xxxxxxx"

    #编译库工程
    #buildLibSg()

    #编译主工程
    buildTarget()
    #打包主工程
    packageIpa()

#生成ipa
def makeIPA():
    for bm in BUILD_MODE:
        execute_makeipa(bm)
    return

#usage
def usage():
    print 'ipa_Builder.py usage:'
    print '-h, --help: 帮助信息.'
    print '-v, --version: 打包的版本号，不输入默认按照Unity PlayerSetting 中设置并打包'
    print '-c, --code : 打包ipa的build值 ，Unity PlayerSetting 中设置并打包'
    print '-project, : 项目工程路径'


#----------------- main ------------------#
if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=u'Unity导出ios- ipa工程设置')
    parser.add_argument('-project',required=True,help=u'项目工程路径')
    fucArgs = parser.parse_args()

    opts,args = getopt.getopt(sys.argv[1:],"hv:c:")
    for op, value in opts:
        if op == "-v":
            VERSION_VALUE = value
        elif op == "-c":
            CODE_VALUE = value
        elif op == "-h":
            usage()
            sys.exit()

    # 先获得系统值
    getBundleVersion()
    # 获取svn最后修改版本号，然后设置自动 xocde版本值
    getSvnVersionHashCode()

    # 下载更新项目工程
    downLoadUnityProject()
    # 修改配置文件
    modifyBundleVersion()

    # 导出xcode工程
    exportXcodeProj(fucArgs.project)

    #lib库
    updatePodFileAndInstall()

    #进行打包

    makeIpaFile()

    makeIPA()
